package com.sky.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
public class OrderIdUtil {
    /**
     * 开始时间戳
     */
    private static final String ORDER_ID = "orderId";

    private static RedisTemplate redisTemplate;

    @Autowired
    public OrderIdUtil(RedisTemplate redisTemplate){
        OrderIdUtil.redisTemplate = redisTemplate;
    }

    /**
     * 获得订单号
     * @return
     */
    public static String nextId() {
        // 生成14位的时间戳(每秒使用新的时间戳当key)
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String timeStamp = timeFormatter.format(LocalDateTime.now());
        // 获得redis-key
        String newKey = ORDER_ID + ":" + timeStamp;
        // 获取自增值（时间戳+自定义key）
        Long increment = redisTemplate.opsForValue().increment(newKey);
        // 设置时间戳生成的key的有效期为2秒
        redisTemplate.expire(newKey, 2, TimeUnit.SECONDS);
        // 获取订单号，时间戳 + 唯一自增Id( 6位数,不过前方补0)
        return timeStamp + String.format("%06d", increment);
    }
}
